﻿using Microsoft.AspNetCore.Hosting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain.Services;
using Volo.Abp.IO;

namespace Hd.AbpCoding.Projects
{
    public class ProjectManager : DomainService, IProjectManager
    {

        protected IProjectRepository Repository { get; }
        private readonly IDomainDescRepository _domainDescRepository;

        protected IWebHostEnvironment WebHostEnvironment { get; }
        protected IDomainDescManager DomainDescManager { get; }

        public ProjectManager(
            IWebHostEnvironment webHostEnvironment,
            IProjectRepository projectRepository,
            IDomainDescRepository domainDescRepository,
            IDomainDescManager domainDescManager)
        {
            Repository = projectRepository;
            WebHostEnvironment = webHostEnvironment;
            _domainDescRepository = domainDescRepository;
            DomainDescManager = domainDescManager;
        }

        public async Task<bool> CheckNameAsync(string name, Guid? excludeId = null)
        {
            var project = await Repository.FindByNameAsync(name);
            if (excludeId.HasValue)
            {
                return project == null || project.Id == excludeId.Value;
            }
            return project == null;
        }

        public async Task GenerateProjectAsync(Guid projectId)
        {
            var domains = await _domainDescRepository.GetListAllAsync(projectId);

            foreach (var domain in domains)
            {
                await DomainDescManager.GenerateDomainAsync(domain.Id, await GetOutputFolderOrDefaultAsync(projectId));
            }
        }



        public async Task<string> GetOutputFolderOrDefaultAsync(Guid projectId)
        {
            var project = await Repository.GetAsync(projectId);

            string outputFolder = Path.Combine(WebHostEnvironment.WebRootPath, "projects", project.Id.ToString());

            DirectoryHelper.CreateIfNotExists(outputFolder);

            return outputFolder;
        }
    }
}
